﻿#include "KeyboardHandler.h"
#include "Utils.h"

KeyboardHandler::KeyboardHandler() : hKeyboardHook(nullptr) {}

KeyboardHandler::~KeyboardHandler() {
  if (hKeyboardHook) {
    UnhookWindowsHookEx(hKeyboardHook);
  }
}

BOOL KeyboardHandler::InstallHook() {
  LOG(_T("KeyboardHandler::InstallHook"));
  hKeyboardHook =
      SetWindowsHookEx(WH_KEYBOARD_LL, KeyboardProc, GetModuleHandle(NULL), 0);
  if (!hKeyboardHook) {
    PrintError(_T("SetWindowsHookEx"), GetLastError());
    return FALSE;
  }
  LOG(_T("KeyboardHandler::InstallHook success"));
  return TRUE;
}

LRESULT CALLBACK KeyboardHandler::KeyboardProc(int nCode, WPARAM wParam,
                                               LPARAM lParam) {
  LOG(_T("KeyboardProc triggered")); // 新增调试日志

  if (nCode >= 0) {
    KBDLLHOOKSTRUCT *pKeyInfo = reinterpret_cast<KBDLLHOOKSTRUCT *>(lParam);
    LOG(_T("Received key event: %d"), pKeyInfo->vkCode); // 新增键码输出

    if (wParam == WM_KEYUP && pKeyInfo->vkCode == VK_F3) {
      SimulateWinH();
      return 1; // 阻止F3键的默认行为
    }
  }
  return CallNextHookEx(NULL, nCode, wParam, lParam);
}

void KeyboardHandler::SimulateWinH() {
  LOG(_T("F3 pressed. Simulating Win+H..."));
  // 构造4个输入事件：按下Win键 → 按下H → 释放H → 释放Win
  INPUT inputs[4] = {};

  // Win键按下（VK_LWIN = Left Windows key）
  inputs[0].type = INPUT_KEYBOARD;
  inputs[0].ki.wVk = VK_LWIN; // Windows键虚拟键码

  // H键按下（ASCII码对应）
  inputs[1].type = INPUT_KEYBOARD;
  inputs[1].ki.wVk = 'H'; // H键的虚拟键码

  // H键释放（添加KEYUP标志）
  inputs[2].type = INPUT_KEYBOARD;
  inputs[2].ki.wVk = 'H';
  inputs[2].ki.dwFlags = KEYEVENTF_KEYUP; // 标识按键释放事件

  // Win键释放
  inputs[3].type = INPUT_KEYBOARD;
  inputs[3].ki.wVk = VK_LWIN;
  inputs[3].ki.dwFlags = KEYEVENTF_KEYUP;

  // 发送组合键序列（需要管理员权限）
  UINT sent = SendInput(4, inputs, sizeof(INPUT));
  if (sent != 4) {
    PrintError(_T("SendInput failed. Sent events:"), sent);
    PrintError(_T("Last system error"), GetLastError());
  }
}
